package com.study.lintcode.my.code_20;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**********************************************************************
 * &lt;p&gt;文件名：Example_1.java &lt;/p&gt;
 * &lt;p&gt;文件描述：(https://www.lintcode.com/problem/search-range-in-binary-search-tree/description)
 * @project_name：LintCode
 * @author zengshunyao
 * @create 2019/1/5 21:56 
 * @history
 * @department：政务事业部
 * Copyright ChengDu Funi Cloud Code Technology Development CO.,LTD 2014 
 *                    All Rights Reserved.
 */
public class Example_11 {
    /**
     * @param root: param root: The root of the binary search tree
     * @param k1:   An integer
     * @param k2:   An integer
     * @return: return: Return all keys that k1<=key<=k2 in ascending order
     */
    public List<Integer> searchRange(TreeNode root, int k1, int k2) {
        // write your code here
        List<Integer> result = new LinkedList<Integer>();
        dfs(root, k1, k2, result);
        return result;
    }

    public void dfs(TreeNode root, int k1, int k2, List<Integer> result) {
        if (root == null) {
            return;
        }
        dfs(root.left, k1, k2, result);

        if (root.val >= k1 && root.val <= k2) {
            result.add(root.val);
        }

        if (root.val < k2) {
            dfs(root.right, k1, k2, result);
        }
    }

    static class TreeNode {
        public int val;
        public TreeNode left, right;

        public TreeNode(int val) {
            this.val = val;
            this.left = this.right = null;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(20);
        root.left = new TreeNode(8);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(12);
        root.right = new TreeNode(22);
        List<Integer> result = new Example_11().searchRange(root, 10, 22);
        System.out.println(Arrays.toString(result.toArray()));
    }
}
